<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="学校" prop="schoolId">
        <el-select v-model="queryParams.schoolId" placeholder="请选择" clearable>
          <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="年级" prop="gradeId" v-if="this.$route.params.id == undefined">
        <el-select v-model="queryParams.gradeId" clearable @change="handleGradeChange">
          <el-option v-for="item in gradeList" :key="item.id" :value="item.id" :label="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="班级" prop="gradeId" v-if="this.$route.params.id == undefined">
        <el-select v-model="queryParams.classId" clearable @change="handleClassChange">
          <el-option v-for="item in classList" :key="item.id" :value="item.id" :label="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学生姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入学生姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="家长手机号" prop="parentsPhone">
        <el-input v-model="queryParams.parentsPhone" placeholder="请输入家长手机号" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="学生状态" prop="status" v-if="this.$route.params.id == undefined">
        <el-select v-model="queryParams.status" @change="handleClassChange">
          <el-option v-for="item in statusList" :key="item.value" :value="item.value" :label="item.label">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" v-if="this.$route.params.id != undefined" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['business:students:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:students:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" v-if="this.$route.params.id != undefined" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['business:students:remove']">批量删除</el-button>
      </el-col>
      <!-- 导入 -->
      <!-- <el-col :span="1.5">
        <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport"
          v-hasPermi="['system:honor:import']">导入</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:students:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <!-- <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据 -->
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-table stripe border :header-cell-style="rowClass" v-loading="loading" :data="studentsList"
      @selection-change="handleSelectionChange">
      <el-table-column :resizable="false" type="selection" width="55" align="center" />
      <el-table-column :resizable="false" label="学生姓名" align="center" prop="name" />
      <el-table-column :resizable="false" label="证件号" align="center" prop="identityNumber" />
      <el-table-column :resizable="false" label="家长手机号" align="center" prop="parentsPhone" />
      <el-table-column :resizable="false" label="年级" align="center" prop="gradeName" />
      <el-table-column :resizable="false" label="班级" align="center" prop="className" />
      <!-- <el-table-column :resizable="false" label="家长信息" align="center" width="150">
        <template #default="scope">
          <el-button @click="parentsList(scope.row)" type="error">家长信息详情</el-button>
        </template>
      </el-table-column> -->
      <el-table-column label="学生性别" align="center">
        <!-- 使用插槽自定义性别显示 -->
        <template slot-scope="scope">
          <span v-if="scope.row.studentsSex === 0">男</span>
          <span v-else-if="scope.row.studentsSex === 1">女</span>
        </template>
      </el-table-column>
      <!-- <el-table-column resizable label="学生状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <div v-if="scope.row.status=='1'" class="flex gap-2">
            <el-tag type="primary" effect="dark" >
              在籍
            </el-tag>
          </div>
          <div v-else-if="scope.row.status=='2'" class="flex gap-2">
            <el-tag type="danger" effect="dark" >
              退学
            </el-tag>
          </div>
        </template>
      </el-table-column> -->
      <el-table-column v-if="this.$route.params.id != undefined" resizable label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['business:students:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['business:students:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改学生信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="学生姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入学生姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="identityNumber">
          <el-input v-model="form.identityNumber" type="text" placeholder="请输入身份证号" maxlength="18" />
        </el-form-item>
        <el-form-item label="学生性别" prop="studentsSex">
          <el-select v-model="form.studentsSex" placeholder="请选择学生性别">
            <el-option label="男" value="0"></el-option>
            <el-option label="女" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="家长手机号" prop="parentsPhone">
          <el-input v-model="form.parentsPhone" placeholder="请输入家长手机号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 家长信息 -->
    <el-dialog :title="title" :visible.sync="openParents" width="50%" append-to-body>
      <el-button v-if="this.$route.params.id != undefined" type="primary" plain icon="el-icon-plus" size="mini" @click="handleAddParents"
        v-hasPermi="['business:parents:add']">新增家长信息</el-button>
      <el-scrollbar height="200px">
        <el-table :data="parentsLists" border>
          <el-table-column label="家长名称" align="center" prop="nickName" />
          <el-table-column label="电话" align="center" prop="phonenumber" />
          <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status == '2' ? 'danger' : 'success'" effect="dark">
                {{ scope.row.status == '2' ? "不活跃" : "活跃" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column v-if="this.$route.params.id != undefined" label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button  size="mini" type="text" icon="el-icon-edit" @click="handleUpdateParents(scope.row)"
                v-hasPermi="['business:parents:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteParents(scope.row)"
                v-hasPermi="['business:parents:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
    </el-dialog>
    <!--添加家长信息-->
    <el-dialog :title="title" :visible.sync="openAddParents" width="500px" append-to-body>
      <el-form ref="parentsForm" :model="parentsForm" :rules="rules" label-width="80px">
        <el-form-item label="家长名称">
          <el-input v-model="parentsForm.name" placeholder="请输入家长名称" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input v-model="parentsForm.phone" placeholder="请输入电话" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormParents">确 定</el-button>
        <el-button @click="cancelParents">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStudents, getStudents, delStudents, addStudents, updateStudents } from "@/api/classSystem/students";
import { listGrades, getGrades, delGrades, addGrades, updateGrades,getschool } from "@/api/gradeSystem/grade";
import { listClasses, getClasses, delClasses, addClasses, updateClasses } from "@/api/classSystem/class";
import { listParents, getParents, delParents, addParents, updateParents } from "@/api/parentsSystem/parents";
import log from "../monitor/job/log";
import { getToken } from "@/utils/auth";
export default {
  name: "Students",
  data () {
    return {
      //学校
      options:[],
      students: {},
      //年级
      gradeList: [],
      //班级
      classList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中学生姓名数组
      studentNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生信息表格数据
      studentsList: [],
      // 家长信息表格数据
      parentsLists: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openParents: false,
      openAddParents: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        schoolId:null,
        name: null,
        classId: null,
        status: null,
        isDeleted: null,
        createdBy: null,
        updatedBy: null,
        parentsPhone: null,
        gradeId: null,
        identityNumber: null,
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/salary/salary/importData"
      },

      // 表单参数
      form: {},
      parentsForm: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "学生姓名不能为空", trigger: "blur" }
        ],
        classId: [
          { required: true, message: "班级ID不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "学生状态：1=在籍, 2=退学不能为空", trigger: "change" }
        ],
        parentsPhone: [
          { required: true, message: "家长手机号不能为空", trigger: "blur" }
        ],
        identityNumber: [
          { required: true, message: "身份证号不能为空", trigger: "blur" }
        ],
      },
      statusList: [{
        "label": "在籍",
        "value": "1"
      }, {
        "label": "退学",
        "value": "2"
      }],
    };
  },
  created () {
    if (this.$route.params.id == undefined) {
      this.getGradeList();
      this.getList();
      this.getclassList();
    } else {
      this.queryParams.classId = this.$route.params.id;
      this.getList();
    }
    this.getschoolList()
  },
  methods: {
    // 查询学校
    async getschoolList(){
      let res=await getschool()
      this.options=res
      console.log("====xue",res);
    },
    //设置table标题样式
    rowClass ({ row, rowIndex }) {
      return 'font-size: 15px; background-color: #FAFAFA;'
    },
    //监听年级选择
    handleGradeChange (newGradeId) {
      this.getclassList(newGradeId);
      this.queryParams.classId = null;
    },
    //监听班级选择
    handleClassChange (newClassId) {
      this.getList(newClassId);
    },
    /** 查询年级信息列表 */
    getGradeList () {
      listGrades(this.queryParams).then(response => {
        this.gradeList = response.rows;
        // if (this.gradeList.length > 0) {
        //   this.queryParams.gradeId = this.gradeList[0].id;
        //   let gradeId = this.gradeList[0].id;
        //   this.getclassList(gradeId);
        // } else {
        //   this.studentsList = [];
        // }
        this.loading = false;
      });
    },
    /**班级列表**/
    getclassList (gradeId) {
      let queryParams = {}
      if (gradeId != null) {
        queryParams.gradeId = gradeId;
      }
      listClasses(queryParams).then(response => {
        this.classList = response.rows;
        // if (this.classList.length > 0) {
        //   this.queryParams.classId = this.classList[0].id;
        //   this.getList();
        // } else {
        //   this.queryParams.classId = null;
        //   this.studentsList = [];
        // }
      });
    },
    /** 查询学生信息列表 */
    getList () {
      this.loading = true;
      listStudents(this.queryParams).then(response => {
        this.studentsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    parentsList (student) {
      this.students.studentId = student.id;
      listParents(this.students).then(response => {
        this.parentsLists = response.rows;
        this.openParents = true;
        this.title = "家长信息";
      });
    },

    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    cancelParents () {
      this.openAddParents = false;
      this.resetParents();
    },
    // 表单重置
    reset () {
      this.form = {
        id: null,
        name: null,
        classId: null,
        status: null,
        isDeleted: null,
        createTime: null,
        updateTime: null,
        createdBy: null,
        updatedBy: null,
        parentsPhone: null
      };
      this.resetForm("form");
    },
    resetParents () {
      this.parentsForm = {
        userId: null,
        name: null,
        phone: null,
      };
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.queryParams.userType = "22";
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      let gradeId = this.queryParams.gradeId;
      let classId = this.queryParams.classId;
      this.resetForm("queryForm");
      this.queryParams.gradeId = gradeId;
      this.queryParams.classId = classId;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
      this.studentNames = selection.map(item => item.name)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      if (this.$route.params.id != undefined) {
        this.form.classId = this.$route.params.id;
      } else {
        this.form.classId = this.queryParams.classId;
      }
      this.open = true;
      this.title = "添加学生信息";
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.reset();
      const id = row.id || this.ids
      getStudents(id).then(response => {
        response.data.studentsSex = String(response.data.studentsSex)
        this.form = response.data;
        this.open = true;
        this.title = "修改学生信息";
      });
    },
    /** 新增按钮操作 */
    handleAddParents () {
      this.resetParents();
      this.openAddParents = true;
      this.title = "新增家长信息";
    },
    /** 修改按钮操作 */
    handleUpdateParents (row) {
      this.resetParents();
      getParents(row.userId).then(response => {
        this.parentsForm.name = response.data.nickName;
        this.parentsForm.userId = response.data.userId;
        this.parentsForm.phone = response.data.phonenumber;
        this.openAddParents = true;
        this.title = "修改家长信息";
      });
    },
    handleDeleteParents (row) {
      this.$modal.confirm('是否确认删除此家长信息').then(function () {
        return delParents(row.userId);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        listParents(this.students).then(response => {
          this.parentsLists = response.rows;
        });
      }).catch(() => { });
      // delParents(row.userId).then(response => {
      //   this.$modal.msgSuccess("删除成功");
      //   listParents(this.students).then(response => {
      //     this.parentsLists = response.rows;
      //   });
      // });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStudents(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            const regex = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12][0-9]|3[01])\d{3}[\dXx]$/;
            if (!regex.test(this.form.identityNumber)) {
              this.$message.error('请输入有效的18位身份证号');
              this.form.identityNumber = null;
            }
            this.form.userType = "22";
            addStudents(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitFormParents () {
      if (this.parentsForm.name == null || this.parentsForm.name == undefined) {
        this.$modal.msgError("家长姓名不能为空");
        return
      } if (this.parentsForm.phone == null || this.parentsForm.phone == undefined) {
        this.$modal.msgError("家长电话不能为空");
        return
      }
      this.$refs["parentsForm"].validate(valid => {
        if (valid) {
          if (this.parentsForm.userId != null) {
            updateParents(this.parentsForm).then(response => {
              this.$modal.msgSuccess("修改家长信息成功");
              this.openAddParents = false;
              listParents(this.students).then(response => {
                this.parentsLists = response.rows;
              });
            });
          } else {
            this.parentsForm.studentId = this.students.studentId;
            console.log("新增==========================", this.parentsForm)
            addParents(this.parentsForm).then(response => {
              this.$modal.msgSuccess("新增家长信息成功");
              this.openAddParents = false;
              listParents(this.students).then(response => {
                this.parentsLists = response.rows;
              });
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const ids = row.id || this.ids;
      const studentName = row.name || this.studentNames
      this.$modal.confirm('是否确认删除学生姓名为"' + studentName + '"的数据项？').then(function () {
        return delStudents(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('business/students/export', {
        ...this.queryParams
      }, `students_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport () {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate () {
      this.download('honor/honor/importTemplate', {
      }, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress (event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess (response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm () {
      this.$refs.upload.submit();
    }
  }
};
</script>
